class Falcon5LanguageSwitcher {
    /**
     * Initialize the language switcher
     */
    constructor(options = {}) {
        if (!falcon5_ajax_config || !falcon5_ajax_config.ajax_url) {
            console.error('falcon5_ajax_config not found or invalid');
            return;
        }

        if (!fc5_utils || typeof fc5_utils.post !== 'function') {
            console.error('fc5_utils.post not found');
            return;
        }

        // 初始化语言切换器
        this.initLanguageSwitcher();
    }

    /**
     * 初始化语言切换器
     */
    initLanguageSwitcher() {
        var self = this;
        // 获取语言设置
        this.fetchLanguageSettings(function(settings) {
            if (!settings) {
                console.error('Failed to fetch language settings');
                return;
            }

            self.settings = settings;
            if (!self.settings.activityTicket) {
                console.error('activityTicket not found');
                return;
            }

            self.originalLanguage = self.settings.originalLanguage ? 
                self.settings.originalLanguage.toLowerCase() : '';
            self.currentLang = self.getCurrentLangFromUrl() || self.originalLanguage;
            self.assetsUri = falcon5_ajax_config.assetsUri;

            console.log('Original language:', self.originalLanguage);
            console.log('Current language:', self.currentLang);
            console.log('Settings:', self.settings);
            console.log('Current language from URL:', self.getCurrentLangFromUrl());

            self.init();
        });
    }

    /**
     * Fetch language settings from server
     * @param {Function} callback - Callback function to handle settings
     */
    fetchLanguageSettings(callback) {
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            { action: 'settings_get_settings' },
            function(response) {
                if (response.code === 1 && response.data) {
                    callback(response.data);
                } else {
                    console.error('Failed to fetch language settings:', response.msg);
                    callback(null);
                }
            },
            function(error) {
                console.error('Request failed:', error);
                callback(null);
            }
        );
    }

    /**
     * Initialize the language switcher by fetching settings and creating the UI
     */
    init() {
        if (!this.settings?.selectedLanguages) return;

        const buttonDesign = this.settings.buttonDesign || {};
        const wrapperSelector = buttonDesign.wrapperSelector;
        const floatingSelector = buttonDesign.floatingSelector;

        // 检查 shortcode wrapper - 独立处理，不参与优先级
        let shortcodeWrappers = document.querySelectorAll('.falcon5_shortcode_wrapper');
        if (shortcodeWrappers.length > 0) {
            shortcodeWrappers.forEach(wrapper => {
                this.container = wrapper;
                this.createShortcodeSwitcher();
            });
        }

        // 优先级1: 检查自定义wrapper
        if (wrapperSelector && wrapperSelector !== '.falcon5_wrapper') {
            const customWrapper = document.querySelector(wrapperSelector);
            if (customWrapper) {
                this.container = customWrapper;
                this.createSwitcher(this.settings.selectedLanguages);
                return;
            }
        }
        
        // 优先级2: 检查floating selector
        if (floatingSelector && floatingSelector !== 'none') {
            let defaultWrapper = document.querySelector('.falcon5_wrapper');
            if (!defaultWrapper) {
                defaultWrapper = document.createElement('div');
                defaultWrapper.className = 'falcon5_wrapper';
                document.body.insertBefore(defaultWrapper, document.body.firstChild);
            }
            this.container = defaultWrapper;
            this.createSwitcher(this.settings.selectedLanguages);
            return;
        }

        // 优先级3: 检查菜单模式
        let menuWrapper = document.querySelector('[data-falcon5-menu-switcher]');
        if (menuWrapper) {
            this.container = menuWrapper;
            this.createMenuSwitcher();
        }
    }

    /**
     * fetch current language from url
     * support subdomain (eg: en.example.com) and subdirectory (eg: example.com/en/)
     * @returns {string|null} language code or null if not found
     */
    getCurrentLangFromUrl() {
        const supportedLangs = 'af|sq|am|ar|hy|az|eu|be|bn|bs|bg|ca|ceb|ny|zh-cn|zh-tw|co|hr|cs|da|nl|en|eo|et|tl|fi|fr|fy|gl|ka|de|el|gu|ht|ha|haw|iw|hi|hmn|hu|is|ig|id|ga|it|ja|jw|kn|kk|km|ko|ku|ky|lo|la|lv|lt|lb|mk|mg|ms|ml|mt|mi|mr|mn|my|ne|no|ps|fa|pl|pt|pa|ro|ru|sm|gd|sr|st|sn|sd|si|sk|sl|so|es|su|sw|sv|tg|ta|te|th|tr|uk|ur|uz|vi|cy|xh|yi|yo|zu';
        const langRegex = new RegExp('^(' + supportedLangs + ')$', 'i');

        // 检查子域名方式
        const hostname = window.location.hostname;
        const hostParts = hostname.split('.');
        if (hostParts.length > 2) {
            const subdomain = hostParts[0].toLowerCase();
            if (langRegex.test(subdomain) && subdomain !== this.originalLanguage) {
                return subdomain;
            }
        }

        // 检查子目录方式
        const pathSegments = window.location.pathname.split('/').filter(Boolean);
        if (pathSegments.length > 0 && langRegex.test(pathSegments[0])) {
            const urlLang = pathSegments[0].toLowerCase();
            if (urlLang !== this.originalLanguage) {
                return urlLang;
            }
        }

        return null;
    }

    /**
     * Bind all necessary events to a switcher element
     * @param {HTMLElement} switcherElement - The switcher element to bind events to
     */
    bindSwitcherEvents(switcherElement) {
        const currentLangBtn = switcherElement.querySelector('.current-language');
        const langList = switcherElement.querySelector('.language-list');
        const langItems = langList.querySelectorAll('.language-item');
        const colors = this.settings?.colors;

        // 切换下拉列表显示状态
        const toggleDropdown = (show) => {
            currentLangBtn.classList.toggle('active', show);
            langList.classList.toggle('show', show);
            switcherElement.classList.toggle('expanded', show);
        };

        // 当前语言按钮点击事件
        currentLangBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            const isShowing = langList.classList.contains('show');
            toggleDropdown(!isShowing);
        });

        // 语言项点击事件
        langItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();

                const langCode = item.dataset.value;
                const langName = item.querySelector('span').textContent;
                const targetUrl = item.dataset.url;

                // 更新UI
                this.currentLang = langCode;
                currentLangBtn.innerHTML = `
                    <img src="${this.assetsUri}/images/flags/${langCode}.svg" alt="${langName} flag">
                    <span>${langName}</span>
                    <span class="falcon5-arrow"></span>
                `;
                
                langItems.forEach(i => i.classList.remove('selected'));
                item.classList.add('selected');
                
                // 关闭下拉列表
                toggleDropdown(false);

                // 跳转到目标URL
                if (targetUrl) {
                    console.log('Redirecting to:', targetUrl);
                    // 直接设置window.location
                    window.location = targetUrl;
                }
            });
        });

        // 点击外部关闭下拉列表
        document.addEventListener('click', (e) => {
            if (!switcherElement.contains(e.target)) {
                toggleDropdown(false);
            }
        });

        // Hover effects
        if (colors?.switcherBgHover) {
            const hoverColor = colors.switcherBgHover;
            const bgColor = colors.switcherBg;
            const shadowColor = colors.switcherBgShadow;
            
            currentLangBtn.addEventListener('mouseenter', () => {
                currentLangBtn.style.background = hoverColor;
            });

            currentLangBtn.addEventListener('mouseleave', () => {
                if (shadowColor) {
                    currentLangBtn.style.background = `${bgColor} linear-gradient(180deg, ${shadowColor} 0%, ${bgColor} 70%)`;
                } else {
                    currentLangBtn.style.background = bgColor;
                }
            });
        }

        // Dropdown items hover effect
        if (colors?.dropdownHover) {
            langItems.forEach(item => {
                item.addEventListener('mouseenter', () => {
                    item.style.backgroundColor = colors.dropdownHover;
                });

                item.addEventListener('mouseleave', () => {
                    item.style.backgroundColor = 'transparent';
                });
            });
        }
    }

    // 修改 buildLanguageUrl 方法，移除可选链操作符
    buildLanguageUrl(lang, originalPath) {
        var langUrl = new URL(window.location.href);
        var isOriginalLanguage = this.originalLanguage === lang.code.toLowerCase();
        var pathSegments = originalPath.split('/').filter(function(segment) {
            return segment.length > 0;
        });
        
        // 移除所有语言代码
        var supportedLangs = 'af|sq|am|ar|hy|az|eu|be|bn|bs|bg|ca|ceb|ny|zh-cn|zh-tw|co|hr|cs|da|nl|en|eo|et|tl|fi|fr|fy|gl|ka|de|el|gu|ht|ha|haw|iw|hi|hmn|hu|is|ig|id|ga|it|ja|jw|kn|kk|km|ko|ku|ky|lo|la|lv|lt|lb|mk|mg|ms|ml|mt|mi|mr|mn|my|ne|no|ps|fa|pl|pt|pa|ro|ru|sm|gd|sr|st|sn|sd|si|sk|sl|so|es|su|sw|sv|tg|ta|te|th|tr|uk|ur|uz|vi|cy|xh|yi|yo|zu';
        var langRegex = new RegExp('^(' + supportedLangs + ')$', 'i');
        var cleanPathSegments = pathSegments.filter(function(segment) {
            return !langRegex.test(segment);
        });

        // 构建新的路径
        var newPath = cleanPathSegments.length > 0 
            ? '/' + cleanPathSegments.join('/')
            : '/';

        // 确保末尾斜杠一致性
        if (originalPath.endsWith('/') && !newPath.endsWith('/') && newPath !== '/') {
            newPath += '/';
        }

        // 获取语言格式设置，使用安全的属性访问
        var languageFormat = this.settings && this.settings.languageFormat;

        if (languageFormat === 'sub-domain') {
            // 子域名模式
            var hostParts = langUrl.hostname.split('.');
            // 获取主域名（移除www和语言子域名）
            var mainDomain = hostParts
                .filter(function(part) {
                    return !langRegex.test(part) && part !== 'www';
                })
                .join('.');

            // 构建新的URL
            var protocol = langUrl.protocol;
            var newHost = isOriginalLanguage ? mainDomain : lang.code + '.' + mainDomain;
            var search = langUrl.search;
            var hash = langUrl.hash;

            return protocol + '//' + newHost + newPath + search + hash;
        } else {
            // 子目录模式
            var newPathWithLang = isOriginalLanguage 
                ? newPath
                : '/' + [lang.code].concat(cleanPathSegments).join('/');

            // 确保末尾斜杠一致性
            langUrl.pathname = originalPath.endsWith('/') && newPathWithLang !== '/' 
                ? newPathWithLang + '/'
                : newPathWithLang;
            
            return langUrl.toString();
        }
    }

    createMenuSwitcher() {
        if (!this.settings?.selectedLanguages) return;
        
        const switcher = document.createElement('div');
        switcher.className = 'falcon5-language-switcher';
        const colors = this.settings?.colors || {};

        // 应用设计选项
        if (this.settings.buttonDesign) {
            if (this.settings.buttonDesign.flagSize) {
                switcher.classList.add(`flag-size-${this.settings.buttonDesign.flagSize}`);
            }
            if (this.settings.buttonDesign.flagStyle) {
                switcher.classList.add(`flag-style-${this.settings.buttonDesign.flagStyle.toLowerCase()}`);
            }
            

            // 设置下拉方向
            if (this.settings.buttonDesign.openDirection) {
                switcher.classList.add(`direction-${this.settings.buttonDesign.openDirection.toLowerCase()}`);
            }
        }


        // 获取当前语言信息
        const currentLang = this.settings.selectedLanguages.find(lang => 
            lang.code === this.currentLang
        ) || this.settings.selectedLanguages[0];
        
        // 创建当前语言按钮
        const currentLangBtn = document.createElement('div');
        currentLangBtn.className = 'current-language';

        // 应用颜色设置到当前语言按钮
        if (colors.switcherText) {
            currentLangBtn.style.color = colors.switcherText;
        }
        if (colors.switcherBorder) {
            currentLangBtn.style.borderColor = colors.switcherBorder;
        }
        if (colors.switcherBg) {
            if (colors.switcherBgShadow) {
                currentLangBtn.style.background = colors.switcherBg + ' linear-gradient(180deg, ' + colors.switcherBgShadow + ' 0%, ' + colors.switcherBg + ' 70%)';
            } else {
                currentLangBtn.style.background = colors.switcherBg;
            }
        }

        currentLangBtn.innerHTML = 
            '<img src="' + this.assetsUri + '/images/flags/' + currentLang.code + '.svg" alt="' + currentLang.name + ' flag">' +
            '<span>' + currentLang.name + '</span>' +
            '<span class="falcon5-arrow"></span>';

        // 创建语言列表
        const langList = document.createElement('div');
        langList.className = 'language-list';
        
        // 应用下拉框背景色
        if (colors.dropdownBg) {
            langList.style.backgroundColor = colors.dropdownBg;
        }

        // 获取原始路径
        const originalPath = document.documentElement.getAttribute('data-original-path') 
            || (history.state && history.state.originalPath) 
            || window.location.pathname;

        this.settings.selectedLanguages.forEach(lang => {
            const langItem = document.createElement('div');
            langItem.className = `language-item${lang.code === this.currentLang ? ' selected' : ''}`;
            langItem.dataset.value = lang.code;

            // 使用新的URL构建方法
            langItem.dataset.url = this.buildLanguageUrl(lang, originalPath);

            const textColor = colors.dropdownText ? `color: ${colors.dropdownText};` : '';
            langItem.innerHTML = `
                <img src="${this.assetsUri}/images/flags/${lang.code}.svg" alt="${lang.name} flag">
                <span style="${textColor}">${lang.name}</span>
            `;
            langList.appendChild(langItem);
        });

        // 组装切换器
        switcher.appendChild(currentLangBtn);
        switcher.appendChild(langList);

        this.container.appendChild(switcher);
        
        // 绑定事件
        this.bindSwitcherEvents(switcher);
    }

    createSwitcher(languages) {
        console.log('Creating switcher element...');
        
        const switcher = document.createElement('div');
        switcher.className = 'falcon5-language-switcher';
        const colors = this.settings?.colors || {};

        // 创建当前语言按钮和语言列表
        const currentLangBtn = this.createCurrentLanguageButton(languages);
        const langList = this.createLanguageList(languages, colors);

        // 获取浮动位置和下拉方向
        const floatingPosition = this.settings.buttonDesign?.floatingSelector || '';
        const openDirection = this.settings.buttonDesign?.openDirection?.toLowerCase() || '';
        
        // 判断按钮和列表的顺序
        const isBottomFloat = floatingPosition.includes('bottom');
        const isTopDirection = openDirection === 'top';
        
        if ((isBottomFloat && isTopDirection) || (!isBottomFloat && isTopDirection)) {
            // 如果是底部浮动且向上展开，或者顶部浮动且向上展开，按钮在列表下面
            switcher.appendChild(langList);
            switcher.appendChild(currentLangBtn);
        } else {
            // 其他情况，按钮在列表上面
            switcher.appendChild(currentLangBtn);
            switcher.appendChild(langList);
        }

        // 应用其他设计选项
        this.applyDesignOptions(switcher);

        this.container.appendChild(switcher);
        
        // 绑定事件
        this.bindSwitcherEvents(switcher);
    }

    // 创建当前语言按钮的辅助方法
    createCurrentLanguageButton(languages) {
        const currentLang = languages.find(lang => lang.code === this.currentLang) || languages[0];
        const currentLangBtn = document.createElement('div');
        currentLangBtn.className = 'current-language';

        // 应用颜色设置
        if (this.settings?.colors) {
            const colors = this.settings.colors;
            if (colors.switcherText) {
                currentLangBtn.style.color = colors.switcherText;
            }
            if (colors.switcherBorder) {
                currentLangBtn.style.borderColor = colors.switcherBorder;
            }
            if (colors.switcherBg) {
                if (colors.switcherBgShadow) {
                    currentLangBtn.style.background = `${colors.switcherBg} linear-gradient(180deg, ${colors.switcherBgShadow} 0%, ${colors.switcherBg} 70%)`;
                } else {
                    currentLangBtn.style.background = colors.switcherBg;
                }
            }
        }

        currentLangBtn.innerHTML = `
            <img src="${this.assetsUri}/images/flags/${currentLang.code}.svg" alt="${currentLang.name} flag">
            <span>${currentLang.name}</span>
            <span class="falcon5-arrow"></span>
        `;

        return currentLangBtn;
    }

    // 创建语言列表的辅助方法
    createLanguageList(languages, colors) {
        const langList = document.createElement('div');
        langList.className = 'language-list';
        
        if (colors.dropdownBg) {
            langList.style.backgroundColor = colors.dropdownBg;
        }

        // 获取原始路径
        const originalPath = document.documentElement.getAttribute('data-original-path') 
            || (history.state && history.state.originalPath) 
            || window.location.pathname;

        languages.forEach(lang => {
            const langItem = document.createElement('div');
            langItem.className = `language-item${lang.code === this.currentLang ? ' selected' : ''}`;
            langItem.dataset.value = lang.code;

            // 使用新的URL构建方法
            langItem.dataset.url = this.buildLanguageUrl(lang, originalPath);

            const textColor = colors.dropdownText ? `color: ${colors.dropdownText};` : '';
            langItem.innerHTML = `
                <img src="${this.assetsUri}/images/flags/${lang.code}.svg" alt="${lang.name} flag">
                <span style="${textColor}">${lang.name}</span>
            `;
            langList.appendChild(langItem);
        });

        return langList;
    }

    // 应用设计选项的辅助方法
    applyDesignOptions(switcher) {
        if (this.settings.buttonDesign) {
            if (this.settings.buttonDesign.flagSize) {
                switcher.classList.add(`flag-size-${this.settings.buttonDesign.flagSize}`);
            }
            if (this.settings.buttonDesign.flagStyle) {
                switcher.classList.add(`flag-style-${this.settings.buttonDesign.flagStyle.toLowerCase()}`);
            }

            const wrapperSelector = this.settings.buttonDesign.wrapperSelector;
            const isDefaultWrapper = !wrapperSelector || wrapperSelector === '.falcon5_wrapper';

            if (isDefaultWrapper && this.settings.buttonDesign.floatingSelector) {
                switcher.classList.add(`position-${this.settings.buttonDesign.floatingSelector}`);
            }

            if (this.settings.buttonDesign.openDirection) {
                switcher.classList.add(`direction-${this.settings.buttonDesign.openDirection.toLowerCase()}`);
            }
        }
    }

    createShortcodeSwitcher() {
        if (!this.settings?.selectedLanguages) return;
        
        const switcher = document.createElement('div');
        switcher.className = 'falcon5-language-switcher';
        const colors = this.settings?.colors || {};

        // 应用设计选项
        if (this.settings.buttonDesign) {
            // 添加国旗大小类
            if (this.settings.buttonDesign.flagSize) {
                switcher.classList.add(`flag-size-${this.settings.buttonDesign.flagSize}`);
            }

            // 添加国旗样式类
            if (this.settings.buttonDesign.flagStyle) {
                switcher.classList.add(`flag-style-${this.settings.buttonDesign.flagStyle.toLowerCase()}`);
            }

            // 设置下拉方向
            if (this.settings.buttonDesign.openDirection) {
                switcher.classList.add(`direction-${this.settings.buttonDesign.openDirection.toLowerCase()}`);
            }
        }

        // 获取当前语言信息
        const currentLang = this.settings.selectedLanguages.find(lang => 
            lang.code === this.currentLang
        ) || this.settings.selectedLanguages[0];
        
        // 创建当前语言按钮
        const currentLangBtn = document.createElement('div');
        currentLangBtn.className = 'current-language';

        // 应用颜色设置
        if (colors.switcherText) {
            currentLangBtn.style.color = colors.switcherText;
        }
        if (colors.switcherBorder) {
            currentLangBtn.style.borderColor = colors.switcherBorder;
        }
        if (colors.switcherBg) {
            if (colors.switcherBgShadow) {
                currentLangBtn.style.background = `${colors.switcherBg} linear-gradient(180deg, ${colors.switcherBgShadow} 0%, ${colors.switcherBg} 70%)`;
            } else {
                currentLangBtn.style.background = colors.switcherBg;
            }
        }

        currentLangBtn.innerHTML = `
            <img src="${this.assetsUri}/images/flags/${currentLang.code}.svg" alt="${currentLang.name} flag">
            <span>${currentLang.name}</span>
            <span class="falcon5-arrow" style="border-color: ${colors.switcherArrow || ''}"></span>
        `;

        // 创建语言列表
        const langList = document.createElement('div');
        langList.className = 'language-list';
        
        // 应用下拉框背景色
        if (colors.dropdownBg) {
            langList.style.backgroundColor = colors.dropdownBg;
        }

        // 获取原始路径
        const originalPath = document.documentElement.getAttribute('data-original-path') 
            || (history.state && history.state.originalPath) 
            || window.location.pathname;

        this.settings.selectedLanguages.forEach(lang => {
            const langItem = document.createElement('div');
            langItem.className = `language-item${lang.code === this.currentLang ? ' selected' : ''}`;
            langItem.dataset.value = lang.code;

            // 获取原始路径
            const originalPath = document.documentElement.getAttribute('data-original-path') 
                || (history.state && history.state.originalPath) 
                || window.location.pathname;

            // 使用新的URL构建方法
            langItem.dataset.url = this.buildLanguageUrl(lang, originalPath);

            const textColor = colors.dropdownText ? `color: ${colors.dropdownText};` : '';
            langItem.innerHTML = `
                <img src="${this.assetsUri}/images/flags/${lang.code}.svg" alt="${lang.name} flag">
                <span style="${textColor}">${lang.name}</span>
            `;
            langList.appendChild(langItem);
        });

        // 组装切换器
        switcher.appendChild(currentLangBtn);
        switcher.appendChild(langList);

        this.container.appendChild(switcher);
        
        // 绑定事件
        this.bindSwitcherEvents(switcher);
    }
}

// Initialize language switcher when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    new Falcon5LanguageSwitcher();
}); 